<?php

namespace app\common\model;

use app\common\util\ErrorCode;
use app\common\util\Tools;
use think\facade\Validate;
use think\Model;

/**
 * Class Auth
 * @package app\common\model
 * 司机表
 */
class trDriver extends Model
{
    protected $pk = 'id';
    protected $resultSetType = 'collection'; //申明结果集是数据集对象（collection），查询结果才能用toArray()方法转为数组
    protected $name = "driver"; //表名
    public $havingData = []; //存放已经获取的数据，减少数据库查询次数

    protected $type = [
        'add_time'  =>  'timestamp:Y-m-d H:i',
        'update_time'  =>  'timestamp:Y-m-d H:i',
    ];

    public function transferField($data){
        if(!$data){
            return [];
        }
        $data = Tools::transferFields($data);
        if(isset($data[0])){
            foreach ($data as $k => $item){
                if(isset($item["avatar"])){
                    $data[$k]["avatarUrl"] = tome_dia(trResource::getValue("url", ["id" => $item["avatar"]]));
                }
                if(isset($item["gender"])){
                    $data[$k]["genderText"] = $item["gender"] == '1' ? "男" : "女";
                }
                if(isset($item["vehicle"])){
                    $data[$k]["vehicleText"] = $this->getAttrByVehicle($item["vehicle"]);
                }
                if(isset($item["driverImg"])){
                    if(strpos($item["driverImg"], ",") !== false){
                        foreach (explode(",", $item["driverImg"]) as $img){
                            $data[$k]["driverImgUrl"][] = ["url" => tome_dia(trResource::getValue("url", ["id" => $img]))];
                        }
                    }else {
                        $data[$k]["driverImgUrl"] = tome_dia(trResource::getValue("url", ["id" => $item["driverImg"]]));
                    }
                }
                if(isset($item["certificateImg"])){
                    if(strpos($item["certificateImg"], ",") !== false) {
                        foreach (explode(",", $item["certificateImg"]) as $img) {
                            $data[$k]["certificateImgUrl"][] = ["url" => tome_dia(trResource::getValue("url", ["id" => $img]))];
                        }
                    }else{
                        $data[$k]["certificateImgUrl"] = tome_dia(trResource::getValue("url", ["id" => $item["certificateImg"]]));
                    }
                }
            }
        }else{
            if(isset($data["avatar"])){
                $data["avatarUrl"] = tome_dia(trResource::getValue("url", ["id" => $data["avatar"]]));
            }
            if(isset($data["gender"])){
                $data["genderText"] = $data["gender"] == '1' ? "男" : "女";
            }
            if(isset($data["vehicle"])){
                $data["vehicleText"] = $this->getAttrByVehicle($data["vehicle"]);
            }
            if(isset($data["driverImg"])){
                if(strpos($data["driverImg"], ",") !== false){
                    foreach (explode(",", $data["driverImg"]) as $img){
                        $data["driverImgUrl"][] = ["url" => tome_dia(trResource::getValue("url", ["id" => $img]))];
                    }
                }else {
                    $data["driverImgUrl"] = tome_dia(trResource::getValue("url", ["id" => $data["driverImg"]]));
                }
            }
            if(isset($data["certificateImg"])){
                if(strpos($data["certificateImg"], ",") !== false) {
                    foreach (explode(",", $data["certificateImg"]) as $img) {
                        $data["certificateImgUrl"][] = ["url" => tome_dia(trResource::getValue("url", ["id" => $img]))];
                    }
                }else {
                    $data["certificateImgUrl"] = tome_dia(trResource::getValue("url", ["id" => $data["certificateImg"]]));
                }
            }
        }
        return $data;
    }

    public function getAttrByVehicle($value){
        if(!empty($value)) {
            $value = explode(",", $value);
            $carTypeModel = new trCarType();
            $text = '';
            foreach ($value as $id){
                if(isset($this->havingData["vehicle"][$id])){
                    $text .= $this->havingData["vehicle"][$id] . ",";
                }else{
                    $this->havingData["vehicle"][$id] = $carTypeModel->getValue("name", ["id" => $id]);
                    $text .= $this->havingData["vehicle"][$id] . ",";
                }
            }
            return substr($text, 0, -1);
        }
        return '';
    }

    //分页获取所有字段数据
    public function getList($field = '*', $filter = [], $page = 1, $limit = 10, $order = "add_time desc", $paginate = true){
        $db = self::where($filter)->field($field)->order($order);
        if($paginate){
            $data = $db->paginate(array('page' => $page, 'list_rows' => $limit));
            if($data){
                $data = $data->toArray();
                $data["data"] = $this->transferField($data["data"]);
                return $data;
            }
        }else{
            if($page && $limit)
                $db->limit($page-1, $limit);
            $data = $db->select();
            $data = $this->transferField($data->toArray());
            return $data;
        }
        return [];
    }

    //根据条件获取数量
    public function getCount($filter){
        if(!empty($filter)){
            return self::where($filter)->count();
        }else{
            return self::count();
        }
    }

    // 操作数据库的数据检查
    public function pre_data_check($data, $filter = []){
        $result = Tools::checkDataBaseFields(self::getTable(), $data);
        if(isset($result["code"])){
            return $result;
        }
        if(isset($data["driving_age"]) && !is_numeric($data["driving_age"])){
            return ErrorCode::code("params_format", "驾龄");
        }
        if(!empty($data["gender"]) && !in_array($data["gender"], [1,2])){
            return ErrorCode::code("customized", "gender参数错误，为1男；2女");
        }
        if(!empty($filter)) {
            if (!isset($filter["id"])) {
                $filter["id"] = $this->getValue("id", $filter);
            }
            $where = [["id", '<>', $filter["id"]]];
        }
        $where[] = ["mall_id", '=', request()->mallData["id"]];
        if(isset($data["mobile"])){
            if(!Validate::isMobile($data["mobile"]))
                return ErrorCode::code("params_format", "手机号");
            $where[] = ["mobile", '=', $data["mobile"]];
            if($this->getCount($where)){
                return ErrorCode::code("mobile_exist");
            }
        }
        if(!empty($data["openid"])){
            $where[] = ["openid", '=', $data["openid"]];
            if($this->getCount($where)){
                return ErrorCode::code("openid_exist");
            }
        }
        if(!empty($data["email"])){
            if(!Validate::isEmail($data["email"]))
                return ErrorCode::code("params_format", "邮箱");
            $where[] = ["email", '=', $data["email"]];
            if($this->getCount($where)){
                return ErrorCode::code("email_exist");
            }
        }
        if(!empty($data["id_card"])){
            if(!Validate::isIdCard($data["id_card"]))
                return ErrorCode::code("id_card_error");
            $where[] = ["id_card", '=', $data["id_card"]];
            if($this->getCount($where)){
                return ErrorCode::code("id_card_error");
            }
        }
        return true;
    }

    //添加
    public function add($data, $getId=false){
        if(!$data)
            return true;
        $result = $this->pre_data_check($data);
        if(isset($result["code"])){
            return $result;
        }
        $data["mall_id"] = request()->mallData["id"];
        if(empty($data["add_time"])) $data["add_time"] = time();
        if($getId){
            return self::insertGetId($data);
        }else{
            return self::insert($data);
        }
    }

    //更新
    public function doUpdate($data, $filter = []){
        if(!$data)
            return true;
        $result = $this->pre_data_check($data, $filter);
        if(isset($result["code"])){
            return $result;
        }
        if(empty($data["update_time"])) $data["update_time"] = time();
        if(self::save($data, $filter)){
            return true;
        }else{
            return false;
        }
    }

    //获取某字段的值
    public function getValue($field, $filter = []){
        if(!is_array($field)){
            return self::where($filter)->value($field);
        }
        return false;
    }

    //获取某字段的所有值
    public function getColumn($field, $filter = [], $key = ''){
        if(!is_array($field)){
            return self::where($filter)->column($field, $key);
        }
        return [];
    }

    //获取多字段数据
    public function getFields($field, $filter = [], $one = true, $toArray = true){ //缓存方法：缓存所有字段，只返回需要的字段
        if($one){
            $data = self::where($filter)->field($field)->find();
            return $data ? ($toArray ? $this->transferField($data->toArray()) : Tools::transferFields($data->getData())) : [];
        }else{
            $data = self::where($filter)->field($field)->select();
            return $data ? ($toArray ? $this->transferField($data->toArray()) : $data) : [];
        }
    }

    //根据ID删除数据
    public function delById($id){
        if(is_array($id)){
            $data = $this->getColumn("openid", [["id", "in", $id]]);
            $result = self::where('id', 'in', $id)->delete();
        }else{
            $data = $this->getColumn("openid", ["id" => $id]);
            $result = self::where('id', $id)->delete();
        }
        if(!empty($data)){ // 修改用户，改成非司机身份
            $userModel = new trUser();
            foreach ($data as $openid){
                $userModel->doUpdate(["user_type" => 0], ["openid" => $openid]);
            }
        }
        return $result;
    }
}